use std::fs;
use dirs::config_dir;
use serde::{Deserialize, Serialize};
use base64::{Engine as _, engine::general_purpose};

#[derive(Serialize, Deserialize, Debug)]
struct UploadResponse {
    code: u16,
    msg: String,
    file_path: String,  // 改为字符串类型
    file_name: String,
}

#[tauri::command]
pub async fn upload_file(file_name: String, file_data: String) -> Result<String, String> {
    println!("Uploading file: {}", file_name);
    let file_data = general_purpose::STANDARD.decode(file_data).map_err(|e| {
        println!("Base64 decode error: {}", e);
        e.to_string()
    })?;

    if file_data.is_empty() {
        println!("Decoded file data is empty!");
        return Err("文件解码失败".to_string());
    }

    // 获取配置目录并设置上传路径
    let base_dir = config_dir().ok_or("无法获取配置目录".to_string())?;
    let upload_dir = base_dir.join("rdmp-tools").join("uploads");

    // 创建目录（如果不存在）
    if !upload_dir.exists() {
        fs::create_dir_all(&upload_dir).map_err(|e| e.to_string())?;
    }

    // 拼接完整文件路径
    let file_path = upload_dir.join(&file_name);
    println!("File will be saved to: {:?}", file_path);

    // 尝试写入文件
    match fs::write(&file_path, &file_data) {
        Ok(_) => {
            let response = UploadResponse {
                code: 200,
                msg: "文件上传成功".to_string(),
                file_path: file_path.to_string_lossy().to_string(), // 转换为字符串
                file_name: file_name.clone(),
            };
            let json_response = serde_json::to_string(&response).map_err(|e| e.to_string())?;
            println!("文件上传成功: {}", json_response);
            
            Ok(json_response)
        }
        Err(e) => {
            let response = UploadResponse {
                code: 500,
                msg: format!("文件保存失败: {}", e),
                file_path: "".to_string(),
                file_name: "".to_string(),
            };
            let json_response = serde_json::to_string(&response).map_err(|e| e.to_string())?;
            println!("文件保存失败: {}", json_response);
            Err(json_response)
        }
    }
}
